package yxy.game.pm2.command.wuchao;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.message.WuchaoMessage;
import yxy.game.pm2.module.wuchao.WuchaoHero;
import yxy.game.pm2.module.wuchao.WuchaoModule;

/** 乌巢 乌巢金疮药 */
@MessageType(proto = Command.WuchaoCure, classtype = WuchaoMessage.WuchaoCureRequest.class)
public class CMD_WuchaoCure extends Command<WuchaoMessage.WuchaoCureRequest> {

	@Override
	public void execute(MessageSource messageSource, WuchaoMessage.WuchaoCureRequest request) {
		String playerCode = messageSource.getTag();
		String heroCode = request.getHero();

		WuchaoMessage.WuchaoCureResponse.Builder response = WuchaoMessage.WuchaoCureResponse.newBuilder();

		WuchaoModule wuchaoModule = WuchaoModule.get(playerCode);
		if (wuchaoModule.getStage() <= 0) {
			send(messageSource, response, Result.WuchaoNotStart);// 没有开始挑战
			return;
		}
		try {
			if (wuchaoModule.tryLock()) {
				if (wuchaoModule.getCure() <= 0) {
					send(messageSource, response, Result.WuchaoCureOut);//  金疮药没了
					return;
				}

				WuchaoHero hero = wuchaoModule.getHeros().get(heroCode);
				if (hero == null) {
					send(messageSource, response, Result.ParamError);// 武将不存在
					return;
				}
				if (hero.getHeroHp() <= 0) {
					send(messageSource, response, Result.WuchaoCureDead);// 武将已死
					return;
				}
				if (hero.getHeroHp() >= 10000) {
					send(messageSource, response, Result.WuchaoCureFull);// 武将满血不需要治疗
					return;
				}

				int hp = hero.getHeroHp() + 5000;
				hero.setHeroHp(hp > 10000 ? 10000 : hp);
				wuchaoModule.setCure(wuchaoModule.getCure() - 1);
				wuchaoModule.set();

				HeroMessage.HeroHp.Builder builder = HeroMessage.HeroHp.newBuilder();
				builder.setCode(hero.getCode());
				builder.setHp(hero.getHeroHp());
				response.setHp(builder);
				response.setCure(wuchaoModule.getCure());

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			wuchaoModule.unlock();
		}
	}

	private void send(MessageSource messageSource, WuchaoMessage.WuchaoCureResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}